package com.chenailin.www.serviceimpl;

import com.chenailin.www.dao.ArticleDao;
import com.chenailin.www.dao.EnterpriseDao;
import com.chenailin.www.dao.KnowledgeBaseDao;
import com.chenailin.www.dao.UserDao;
import com.chenailin.www.daoimpl.ArticleDaoImpl;
import com.chenailin.www.daoimpl.EnterpriseDaoImpl;
import com.chenailin.www.daoimpl.KnowledgeBaseDaoImpl;
import com.chenailin.www.daoimpl.UserDaoImpl;
import com.chenailin.www.model.pojo.*;
import com.chenailin.www.model.vo.*;
import com.chenailin.www.service.SearchService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author evi
 */
public class SearchServiceImpl implements SearchService {
    private final ArticleDao articleDao = new ArticleDaoImpl();
    private final KnowledgeBaseDao knowledgeBaseDao = new KnowledgeBaseDaoImpl();
    private final UserDao userDao = new UserDaoImpl();
    private final EnterpriseDao enterpriseDao = new EnterpriseDaoImpl();

    @Override
    public SearchResultVO search(String keyword, int page, int size) {
        SearchResultVO result = new SearchResultVO();

        // 搜索文章
        List<ArticleVO> articles = searchArticles(keyword, page, size);
        result.setArticles(articles);

        // 搜索知识库
        List<KnowledgeBaseVO> knowledgeBases = searchKnowledgeBases(keyword, page, size);
        result.setKnowledgeBases(knowledgeBases);

        // 搜索用户
        List<UserVO> users = searchUsers(keyword, page, size);
        result.setUsers(users);

        // 设置总数
        result.setTotal(articles.size() + knowledgeBases.size() + users.size());

        return result;
    }

    @Override
    public List<ArticleVO> searchArticles(String keyword, int page, int size) {
        int offset = (page - 1) * size;
        List<Article> articles = articleDao.searchByKeyword(keyword, size, offset);

        // 只返回公开知识库的文章
        List<ArticleVO> result = new ArrayList<>();
        for (Article article : articles) {
            KnowledgeBase kb = knowledgeBaseDao.findById(article.getKnowledgeId());
            if (kb != null && kb.getIsPublic()) {
                ArticleVO vo = new ArticleVO();
                vo.setId(article.getId());
                vo.setTitle(article.getTitle());
                vo.setContent(article.getContent());
                vo.setKnowledgeId(article.getKnowledgeId());
                vo.setAuthorId(article.getAuthorId());
                // TODO: 设置作者信息（需要UserDao支持）
                vo.setViewCount(article.getViewCount());
                vo.setLikeCount(article.getLikeCount());
                vo.setCommentCount(article.getCommentCount());
                vo.setCreateTime(article.getCreateTime());

                result.add(vo);
            }
        }

        return result;
    }

    @Override
    public List<KnowledgeBaseVO> searchKnowledgeBases(String keyword, int page, int size) {
        // TODO: 实现知识库搜索，需要在KnowledgeBaseDao添加搜索方法
        // 暂时返回所有公开知识库
        List<KnowledgeBase> knowledgeBases = knowledgeBaseDao.findPublicBases();

        return knowledgeBases.stream()
                .filter(kb -> kb.getName().contains(keyword) ||
                        (kb.getDescription() != null && kb.getDescription().contains(keyword)))
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<UserVO> searchUsers(String keyword, int page, int size) {
        // TODO: 实现用户搜索，需要在UserDao添加搜索方法
        // 暂时返回空列表
        return new ArrayList<>();
    }

//    @Override
//    public SearchResultVO globalSearch(String keyword, Long userId, int page, int size) {
//        if (keyword == null || keyword.trim().isEmpty()) {
//            throw new BusinessException("搜索关键词不能为空");
//        }
//
//        SearchResultVO result = new SearchResultVO();
//
//        // 分页参数
//        int offset = (page - 1) * size;
//
//        // 搜索文章
//        List<ArticleVO> articles = searchArticles(keyword, 1, size);
//        result.setArticles(articles);
//
//        // 搜索知识库
//        List<KnowledgeBaseVO> knowledgeBases = searchKnowledgeBases(keyword, 1, size);
//        result.setKnowledgeBases(knowledgeBases);
//
//        // 搜索用户
//        List<UserVO> users = searchUsers(keyword, 1, size);
//        result.setUsers(users);
//
//        // 搜索企业
//        List<EnterpriseVO> enterprises = searchEnterprises(keyword, userId, 1, size);
//        result.setEnterprises(enterprises);
//
//        // 设置总数和分页信息
//        int total = articles.size() + knowledgeBases.size() + users.size() + enterprises.size();
//        result.setTotal(total);
//        result.setCurrentPage(page);
//        result.setPageSize(size);
//        result.setTotalPages((int) Math.ceil((double) total / size));
//
//        return result;
//    }

//    @Override
//    public List<EnterpriseVO> searchEnterprises(String keyword, Long userId, int page, int size) {
//        if (keyword == null || keyword.trim().isEmpty()) {
//            throw new BusinessException("搜索关键词不能为空");
//        }
//
//        // 分页参数
//        int offset = (page - 1) * size;
//
//        // 搜索企业
//        List<Enterprise> enterprises = enterpriseDao.searchByKeyword(keyword, size, offset);
//
//        // 过滤结果：只返回用户所在的企业
//        List<EnterpriseVO> result = new ArrayList<>();
//        for (Enterprise enterprise : enterprises) {
//            // 检查用户是否是企业成员
//            EnterpriseMember member = enterpriseMemberDao.findByEnterpriseAndUser(enterprise.getId(), userId);
//            if (member != null) {
//                result.add(convertToVO(enterprise, userId));
//            }
//        }
//
//        return result;
//    }

    // 企业转换为VO的辅助方法
    private EnterpriseVO convertToVO(Enterprise enterprise, Long userId) {
        EnterpriseVO vo = new EnterpriseVO();
        vo.setId(enterprise.getId());
        vo.setName(enterprise.getName());
//        vo.setDescription(enterprise.getDescription());
//        vo.setLogoUrl(enterprise.getLogoUrl());
        vo.setCreatorId(enterprise.getCreatorId());

        // 获取创建者信息
        User creator = userDao.findById(enterprise.getCreatorId());
        if (creator != null) {
            vo.setCreatorName(creator.getUsername());
            vo.setCreatorAvatar(creator.getAvatar());
        }

//        // 设置成员数量
//        int memberCount = enterpriseMemberDao.countMembers(enterprise.getId());
//        vo.setMemberCount(memberCount);
//
//        // 设置当前用户角色
//        EnterpriseMember member = enterpriseMemberDao.findByEnterpriseAndUser(enterprise.getId(), userId);
//        if (member != null) {
//            vo.setCurrentUserRole(member.getRole());
//        }

        vo.setCreateTime(enterprise.getCreateTime());
        vo.setUpdateTime(enterprise.getUpdateTime());

        return vo;
    }

    private KnowledgeBaseVO convertToVO(KnowledgeBase kb) {
        KnowledgeBaseVO vo = new KnowledgeBaseVO();
        vo.setId(kb.getId());
        vo.setName(kb.getName());
        vo.setDescription(kb.getDescription());
        vo.setCoverUrl(kb.getCoverUrl());
        vo.setIsPublic(kb.getIsPublic());
        vo.setCreatorId(kb.getCreatorId());
        // TODO: 设置创建者信息（需要UserDao支持）
        vo.setCreateTime(kb.getCreateTime());
        return vo;
    }
}